<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="父分类" prop="parentId">
        <el-input
          v-model="queryParams.parentId"
          placeholder="请输入父分类ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类名称" prop="categoryName">
        <el-input
          v-model="queryParams.categoryName"
          placeholder="请输入分类名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类编码" prop="categoryCode">
        <el-input
          v-model="queryParams.categoryCode"
          placeholder="请输入分类编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类图标" prop="categoryIcon">
        <el-input
          v-model="queryParams.categoryIcon"
          placeholder="请输入分类图标"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="排序" prop="sortOrder">
        <el-input
          v-model="queryParams.sortOrder"
          placeholder="请输入排序"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createdTime">
        <el-date-picker clearable
          v-model="queryParams.createdTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间" prop="updatedTime">
        <el-date-picker clearable
          v-model="queryParams.updatedTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择更新时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:categories:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:categories:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:categories:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:categories:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="flattenedList" 
      @selection-change="handleSelectionChange"
      row-key="categoryId"
      stripe
      border
      highlight-current-row
      class="common-table"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="分类名称" width="300" show-overflow-tooltip>
        <template slot-scope="scope">
          <span :style="{paddingLeft: (scope.row.level || 0) * 20 + 'px'}">
            <!-- 手动添加展开/收起按钮 -->
            <span v-if="scope.row.children && scope.row.children.length > 0" 
                  @click.stop="toggleExpand(scope.row)" 
                  style="cursor: pointer; margin-right: 8px; display: inline-block; width: 20px; height: 20px; line-height: 20px; text-align: center; border: 1px solid #ddd; border-radius: 3px; background: #f5f5f5;">
              <i :class="scope.row.expanded ? 'el-icon-caret-bottom' : 'el-icon-caret-right'" style="font-size: 12px;"></i>
            </span>
            <span v-else style="display: inline-block; width: 28px;"></span>
            
            <i v-if="scope.row.categoryIcon && scope.row.categoryIcon.startsWith('http')" 
               style="margin-right: 8px;">
              <el-image
                style="width: 20px; height: 20px; vertical-align: middle;"
                :src="scope.row.categoryIcon"
                fit="cover"
              />
            </i>
            <i v-else-if="scope.row.categoryIcon" 
               :class="scope.row.categoryIcon" 
               style="margin-right: 8px; font-size: 16px; vertical-align: middle;"></i>
            {{ scope.row.categoryName }}
            <el-tag v-if="scope.row.children && scope.row.children.length > 0" 
                    size="mini" 
                    type="info" 
                    style="margin-left: 8px;">
              {{ scope.row.children.length }}个子分类
            </el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="编码" align="center" prop="categoryCode" width="120" />
      <el-table-column label="排序" align="center" prop="sortOrder" width="80" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="描述" prop="description" show-overflow-tooltip />
      <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:categories:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:categories:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="父分类ID，0为顶级分类" prop="parentId">
              <el-input v-model="form.parentId" placeholder="请输入父分类ID，0为顶级分类" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类名称" prop="categoryName">
              <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类编码" prop="categoryCode">
              <el-input v-model="form.categoryCode" placeholder="请输入分类编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类图标" prop="categoryIcon">
              <el-input v-model="form.categoryIcon" placeholder="请输入分类图标" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sortOrder">
              <el-input v-model="form.sortOrder" placeholder="请输入排序" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="分类描述" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createdTime">
              <el-date-picker clearable style="width: 100%"
                v-model="form.createdTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择创建时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新时间" prop="updatedTime">
              <el-date-picker clearable style="width: 100%"
                v-model="form.updatedTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择更新时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCategories, getCategories, delCategories, addCategories, updateCategories, updateCategoriesStorage } from "@/api/system/categories";

export default {
  name: "Categories",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备分类表格数据
      categoriesList: [],
      // 展开的行键值
      expandedKeys: [],
      flattenedList: [], // 手动展开的平均列表
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        parentId: null,
        categoryName: null,
        categoryCode: null,
        categoryIcon: null,
        sortOrder: null,
        status: null,
        description: null,
        createdTime: null,
        updatedTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "父分类ID，0为顶级分类不能为空", trigger: "blur" }
        ],
        categoryName: [
          { required: true, message: "分类名称不能为空", trigger: "blur" }
        ],
        categoryCode: [
          { required: true, message: "分类编码不能为空", trigger: "blur" }
        ],
        sortOrder: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态：0-禁用，1-启用不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询设备分类列表 */
    getList() {
      this.loading = true;
      console.log('发送查询请求，参数：', this.queryParams);
      listCategories(this.queryParams).then(response => {
        console.log('接收到响应数据：', response);
        console.log('分类列表数据：', response.rows);
        console.log('数据总数：', response.total);
        
        this.categoriesList = response.rows;
        this.total = response.total;
        this.loading = false;
        
        // 检查树结构
        if (response.rows && response.rows.length > 0) {
          console.log('第一个分类项：', response.rows[0]);
          console.log('是否有children属性：', response.rows[0].hasOwnProperty('children'));
          
          // 初始化数据结构
          this.initializeTreeData(response.rows);
          
          // 生成平均列表用于显示
          this.flattenedList = this.flattenTreeData(response.rows, 0);
          
          console.log('平均列表数据:', this.flattenedList);
        }
      }).catch(error => {
        console.error('查询分类列表失败：', error);
        this.loading = false;
      });
    },
    // 初始化树形数据结构
    initializeTreeData(data) {
      data.forEach(item => {
        // 确保 children是数组
        if (!item.children) {
          item.children = [];
        }
        // 设置初始展开状态
        item.expanded = false;
        item.level = 0;
        
        // 递归初始化子节点
        this.initializeChildrenData(item.children, 1);
      });
    },
    // 初始化子节点数据
    initializeChildrenData(children, level) {
      children.forEach(child => {
        child.expanded = false;
        child.level = level;
        if (!child.children) {
          child.children = [];
        }
        this.initializeChildrenData(child.children, level + 1);
      });
    },
    // 将树形数据平均化为列表
    flattenTreeData(data, level) {
      let result = [];
      data.forEach(item => {
        // 添加当前项
        result.push({
          ...item,
          level: level
        });
        
        // 如果展开且有子节点，递归添加子节点
        if (item.expanded && item.children && item.children.length > 0) {
          result = result.concat(this.flattenTreeData(item.children, level + 1));
        }
      });
      return result;
    },
    // 切换展开/收起状态
    toggleExpand(row) {
      console.log('=== 点击展开按钮 ===');
      console.log('切换展开状态:', row.categoryName, '当前状态:', row.expanded);
      console.log('当前行数据:', row);
      
      // 如果是一级分类（level为0或parentId为0），需要先收起其他一级分类
      if (row.level === 0 || row.parentId === 0) {
        // 如果当前要展开一级分类，先收起所有其他一级分类
        if (!row.expanded) {
          this.collapseAllTopLevelCategories(row.categoryId);
        }
      }
      
      // 切换展开状态
      row.expanded = !row.expanded;
      
      // 更新原始数据中的状态
      this.updateOriginalDataExpanded(this.categoriesList, row.categoryId, row.expanded);
      
      // 重新生成平均列表
      this.flattenedList = this.flattenTreeData(this.categoriesList, 0);
      
      console.log('展开状态已更新:', row.categoryName, '新状态:', row.expanded);
      console.log('新的平均列表数量:', this.flattenedList.length);
    },
    // 收起所有一级分类（除了指定的分类ID）
    collapseAllTopLevelCategories(excludeCategoryId) {
      console.log('收起所有一级分类，除了:', excludeCategoryId);
      this.categoriesList.forEach(item => {
        // 只处理一级分类（parentId为0或null）且不是当前点击的分类
        if ((item.parentId === 0 || item.parentId === null) && item.categoryId !== excludeCategoryId) {
          if (item.expanded) {
            console.log('收起一级分类:', item.categoryName);
            item.expanded = false;
            // 递归收起所有子分类
            this.collapseAllChildren(item.children);
          }
        }
      });
    },
    // 递归收起所有子分类
    collapseAllChildren(children) {
      if (children && children.length > 0) {
        children.forEach(child => {
          child.expanded = false;
          this.collapseAllChildren(child.children);
        });
      }
    },
    // 更新原始数据中的展开状态
    updateOriginalDataExpanded(data, categoryId, expanded) {
      data.forEach(item => {
        if (item.categoryId === categoryId) {
          item.expanded = expanded;
        } else if (item.children && item.children.length > 0) {
          this.updateOriginalDataExpanded(item.children, categoryId, expanded);
        }
      });
    },
    // 获取所有可展开的键值
    getAllExpandableKeys(data) {
      let keys = [];
      data.forEach(item => {
        if (item.children && item.children.length > 0) {
          keys.push(item.categoryId);
          // 递归获取子节点的键值
          keys = keys.concat(this.getAllExpandableKeys(item.children));
        }
      });
      return keys;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        categoryId: null,
        parentId: null,
        categoryName: null,
        categoryCode: null,
        categoryIcon: null,
        sortOrder: null,
        status: null,
        description: null,
        createdTime: null,
        updatedTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.categoryId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备分类";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const categoryId = row.categoryId || this.ids
      getCategories(categoryId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备分类";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.categoryId != null) {
            updateCategories(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              // 同步更新localStorage中的分类数据
              updateCategoriesStorage().catch(error => {
                console.error('更新localStorage分类数据失败:', error);
              });
            });
          } else {
            addCategories(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              // 同步更新localStorage中的分类数据
              updateCategoriesStorage().catch(error => {
                console.error('更新localStorage分类数据失败:', error);
              });
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const categoryIds = row.categoryId || this.ids;
      this.$modal.confirm('是否确认删除设备分类编号为"' + categoryIds + '"的数据项？').then(function() {
        return delCategories(categoryIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
        // 同步更新localStorage中的分类数据
        updateCategoriesStorage().catch(error => {
          console.error('更新localStorage分类数据失败:', error);
        });
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/categories/export', {
        ...this.queryParams
      }, `categories_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
